package com.zsy.aspect;

import cn.hutool.json.JSONUtil;
import com.zsy.pojo.OperateLog;
import com.zsy.service.LogService;
import com.zsy.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-09-14 19:54
 **/
@Component
@Slf4j
@Aspect
public class RecordLogAspect {
    @Autowired
    private LogService logService;
    @Around("@annotation(com.zsy.annoation.ReportLogAnno)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1.记录方法执行开始时间
        long begin = System.currentTimeMillis();
        // 2.执行方法
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        // 3.记录方法执行结束时间
        long end = System.currentTimeMillis();
        // 获取方法的类名
        String className = joinPoint.getClass().getName();
        // 获取方法的名称
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getMethod().getName();
        // 获取方法的请求参数
        Object[] args = joinPoint.getArgs();
        // 给实体类赋值
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        // 转换为json类型
        if (args != null && args.length > 0)
            operateLog.setMethodParams(JSONUtil.toJsonStr(args));
        if (proceed != null)
            operateLog.setReturnValue(JSONUtil.toJsonStr(proceed));
        operateLog.setCostTime(end - begin);
        logService.insert(operateLog);
        return proceed;
    }
    // 获取当前操作用户id
    public Integer getCurrentUserId(){
        return CurrentHolder.getCurrentUserId();
    }
}
